<template>
  <div class="app-container">
    <div class="search-container">
      <el-form :model="searchParam" :inline="true">
        <el-form-item label="工厂">
          <el-select
            v-model="searchParam.plantId"
            clearable
            placeholder="请选择工厂"
          >
            <el-option
              v-for="item in plants"
              :key="item.key"
              :label="item.label"
              :value="item.key"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="供应商">
          <el-select
            v-model="searchParam.partnerId"
            clearable
            placeholder="请选择供应商"
          >
            <el-option
              v-for="item in partners"
              :key="item.id"
              :label="item.partnerName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="到货日期">
          <el-date-picker
            v-model="searchParam.arriveDateSearch"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            @change="getarriveDate"
          />
        </el-form-item>
        <el-form-item label="物料号">
          <el-input
            v-model="searchParam.materialNumber"
            placeholder="请输入物料号"
            clearable
            @keyup.enter="search"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="search">
            <i-ep-search />
            搜索
          </el-button>
          <el-button @click="reset">
            <i-ep-refresh />
            重置
          </el-button>
          <!--          <el-button-->
          <!--            class="ml-3"-->
          <!--            @click="-->
          <!--              useDownload(-->
          <!--                '/srm/srmorderschedule/export',-->
          <!--                '采购计划',-->
          <!--                searchParam-->
          <!--              )-->
          <!--            "-->
          <!--          >-->
          <!--            <template #icon>-->
          <!--              <i-ep-download />-->
          <!--            </template>-->
          <!--            导出-->
          <!--          </el-button>-->
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never" class="table-container">
      <template #header>
        <el-button type="primary" @click="openDialog()">
          <i-ep-plus />
          新增
        </el-button>
        <el-button
          type="danger"
          :disabled="ids.length === 0"
          @click="handleTableDelete()"
        >
          <i-ep-delete />
          批量删除
        </el-button>
        <el-button type="primary" @click="excelBoxOpen"> 导入</el-button>
        <el-button type="primary" @click="synchronizationOpen">
          同步
        </el-button>
        <el-button
          type="success"
          :disabled="ids.length === 0"
          @click="batchConfirm()"
        >
          批量确认
        </el-button>
      </template>
      <el-table
        ref="dataTableRef"
        v-loading="loading"
        :data="tableData"
        highlight-current-row
        border
        @selection-change="handleSelectionChange"
        :header-cell-style="{ textAlign: 'center' }"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column
          label="计划编号"
          prop="orderNo"
          min-width="170"
          align="center"
          show-overflow-tooltip
        />
        <el-table-column
          label="工厂编号"
          prop="plantCode"
          min-width="120"
          show-overflow-tooltip
        />
        <el-table-column
          label="工厂名称"
          prop="plantName"
          min-width="200"
          show-overflow-tooltip
        />
        <el-table-column
          label="供应商编号"
          prop="partnerCode"
          min-width="120"
          show-overflow-tooltip
          align="left"
        />
        <el-table-column
          label="供应商名称"
          prop="partnerName"
          min-width="200"
          show-overflow-tooltip
          align="left"
        />
        <el-table-column
          label="物料号"
          prop="materialNumber"
          min-width="120"
          show-overflow-tooltip
          align="left"
        />
        <el-table-column
          label="物料名"
          prop="materialName"
          min-width="150"
          show-overflow-tooltip
          align="left"
        />
        <el-table-column
          label="到货日期"
          prop="arriveDate"
          min-width="100"
          show-overflow-tooltip
          format="YYYY-MM-DD"
          align="center"
        />
        <el-table-column
          label="要货地点"
          prop="storageLocationName"
          min-width="100"
          show-overflow-tooltip
          align="left"
        />
        <el-table-column
          label="采购数量"
          prop="planQuantity"
          min-width="100"
          show-overflow-tooltip
          align="right"
        />
        <el-table-column
          label="采购周期类型"
          prop="purchasingCycleType"
          min-width="120"
          show-overflow-tooltip
          align="center"
        >
          <template #default="{ row }">
            <el-tag>
              <span v-show="row.purchasingCycleType == '1'">短周期订单</span>
              <span v-show="row.purchasingCycleType == '2'">长周期测试</span>
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          label="启用状态"
          prop="purchasingCycleType"
          min-width="100"
          show-overflow-tooltip
          align="center"
        >
          <template #default="{ row }">
            <el-tag>
              <span v-show="row.enabled == '0'">停用</span>
              <span v-show="row.enabled == '1'">启用</span>
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          label="计划协议号"
          prop="purchasePlanNumber"
          min-width="100"
          show-overflow-tooltip
        />
        <el-table-column
          label="可满足数量"
          prop="agreeQuantity"
          min-width="100"
          show-overflow-tooltip
          align="right"
        />
        <el-table-column
          label="反馈时间"
          prop="replyTime"
          min-width="160"
          show-overflow-tooltip
          align="center"
        />
        <el-table-column
          label="更新时间"
          prop="lastUpdateTime"
          min-width="160"
          show-overflow-tooltip
          align="center"
        />
        <el-table-column
          label="更新人"
          prop="lastUpdatedUserName"
          min-width="100"
          show-overflow-tooltip
          align="center"
        />
        <el-table-column fixed="right" label="操作" width="240" align="center">
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              link
              @click="openDialog(scope.row)"
            >
              <i-ep-edit />
              编辑
            </el-button>
            <el-button
              type="primary"
              size="small"
              link
              @click="handleTableDelete(scope.row.id)"
            >
              <i-ep-delete />
              删除
            </el-button>
            <el-button
              type="primary"
              size="small"
              link
              @click="isEnabled(scope.row)"
            >
              <span v-show="scope.row.enabled == '1'">停用</span>
              <span v-show="scope.row.enabled == '0'">启用</span>
            </el-button>
            <el-button
              type="primary"
              size="small"
              link
              @click="confirm(scope.row.id)"
              :disabled="scope.row.orderScheduleState == 4"
            >
              确认
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 导入-->
      <el-dialog
        :close-on-click-modal="false"
        title="订货计划数据导入"
        v-model="excelBox"
        width="416px"
      >
        <el-col :span="24" style="margin-bottom: 10px; right: 0">
          <span style="margin-right: 20px">开始日期</span>
          <el-date-picker
            v-model="beginDate"
            type="date"
            style="width: 300px"
            clearable
            :disabled-date="disabledDate"
          />
        </el-col>
        <el-col :span="24">
          <span style="margin-right: 20px">结束日期</span>
          <el-date-picker
            v-model="endDate"
            type="date"
            style="width: 300px"
            clearable
            :disabled-date="disabledDate"
          />
        </el-col>
        <!--        导入模板-->
        <!--        <el-col :span="24">-->
        <!--          <div>-->
        <!--            <el-button-->
        <!--              style="margin-top: 10px"-->
        <!--              @click="-->
        <!--                useDownload(-->
        <!--                  '/srm/srmorderschedule/exportTemp',-->
        <!--                  '订货计划上传模板',-->
        <!--                  searchParam-->
        <!--                )-->
        <!--              "-->
        <!--            >-->
        <!--              <template #icon>-->
        <!--                <i-ep-download />-->
        <!--              </template>-->
        <!--              订货计划上传模板下载-->
        <!--            </el-button>-->
        <!--          </div>-->
        <!--        </el-col>-->
        <div style="margin-top: 10px">
          <input
            class="crop-input"
            type="file"
            name="image"
            accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
            ref="onload_exl"
            @change="getfilepath"
            style="margin-right: 63px"
          />
          <el-button
            @click="upload"
            :disabled="uploadBtn"
            style="cursor: pointer"
            type="primary"
            >上传
          </el-button>
        </div>
      </el-dialog>
      <!--同步数据-->
      <el-dialog
        :close-on-click-modal="false"
        v-model="synchronization"
        title="同步数据"
        width="420"
        :before-close="handleClose"
      >
        <el-row>
          <el-col :span="24" style="margin-bottom: 10px">
            <span style="margin-right: 20px">开始日期</span>
            <el-date-picker
              v-model="beginDate"
              type="date"
              style="width: 300px"
              clearable
              :disabled-date="disabledDate"
            />
          </el-col>
          <el-col :span="24">
            <span style="margin-right: 20px">结束日期</span>
            <el-date-picker
              v-model="endDate"
              type="date"
              style="width: 300px"
              clearable
              :disabled-date="disabledDate"
            />
          </el-col>
          <el-col style="margin-top: 15px">
            <div style="margin-left: 315px">
              <el-button type="primary" @click="synchronizationClose">
                同步
              </el-button>
            </div>
          </el-col>
        </el-row>
      </el-dialog>
      <el-pagination
        :background="true"
        :current-page="pageable.pageNum"
        :page-size="pageable.pageSize"
        :page-sizes="[10, 25, 50, 100]"
        :total="pageable.total"
        layout="total, sizes, prev, pager, next, jumper"
        class="mt-[20px]"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <srmorderschedule-edit
      :visible="addDialog.visible"
      :title="addDialog.title"
      :data="addDialog.data"
      @reset-table="(id: string) => (id?.length ? getTableList() : reset())"
      :is-readonly="addDialog.readvisible"
      @change-visible="changeVisible"
    />
  </div>
</template>

<script setup lang="ts">
import { useTable, useDownload, useDictionary } from "@/utils/useTable";
import request from "@/utils/request";

defineOptions({
  name: "SRMSRMORDERSCHEDULE",
  inheritAttrs: false,
});
// 工厂
let plants = ref([]);
// 供应商
let partners = ref([]);
// 开始时间结束时间
let beginDate = ref();
let endDate = ref();

const dialogVisible = ref(false);
const synchronization = ref(false);
// 导入excel
const uploadApi = "/srm/core/srmorderschedule/upload";
const excelBox = ref(false);
const uploadBtn = ref(false);
const uploadFile = ref("");
const fileName = ref("");
const disabledDate = (time: Date) => {
  return time.getTime() <= Date.now() - 8.64e7;
};
// 对话框点击其他区域关闭
const handleClose = (done: () => void) => {
  done();
};

// 请求参数
const requestApi = "/srm/core/srmorderschedule/queryByPage";

// 是否需要分页
const pagination = true;

const initParam = {};

// 初始化搜索参数数据
const searchParamInit = {
  plantName: "",
  partnerCode: "",
  materialNumber: "",
  arriveDateSearch: [],
  arriveDateStart: "",
  arriveDateEnd: "",
};

const deleteParam = {
  api: "/srm/core/srmorderschedule/delete",
  data: {},
};

// 数据请求错误后处理
function requestError() {}

function dataCallBack(res: any[]) {
  for (let i = 0; i < res.length; i++) {
    res[i].arriveDate = formatDate(res[i].arriveDate);
  }
  return res;
}

function formatDate(date: any) {
  let d = new Date(date),
    month = "" + (d.getMonth() + 1),
    day = "" + d.getDate(),
    year = d.getFullYear();

  if (month.length < 2) month = "0" + month;
  if (day.length < 2) day = "0" + day;

  return [year, month, day].join("-");
}

// const dataCallBack = ref(undefined); // 无需二次数据处理&不传赞数也行

// 表格操作 Hooks
const {
  tableData,
  pageable,
  searchParam,
  ids,
  getTableList,
  search,
  reset,
  handleSizeChange,
  handleCurrentChange,
  handleSelectionChange,
  handleTableDelete,
  loading,
}: any = useTable(
  requestApi,
  initParam,
  searchParamInit,
  pagination,
  dataCallBack,
  requestError,
  deleteParam
);

onMounted(() => {
  getTableList();
  getPlants();
  getPartners();
});

const addDialog = reactive<DialogOption>({
  visible: false,
  readvisible: false,
  title: "",
  data: {},
});

// 供应商查询
async function getPartners() {
  const data = await request({
    url: "/srm/core/mdmpartner/getList",
    method: "post",
    data: {},
  });
  partners.value = data.data;
}

// 工厂查询
async function getPlants() {
  const data = await request({
    url: "/srm/core/common/getPlantList",
    method: "get",
  });
  plants.value = data.data;
}

// 查询详情
async function getInfo(id: string) {
  addDialog.data = {};
  request({
    url: `/srm/core/srmorderschedule/get/${id}`,
    method: "get",
  })
    .then((data) => {
      addDialog.data = data.data;
      getAgreement(data.data.purchasePlanNumber);
    })
    .catch((res) => {
      // console.log(res);
    });
}

// 根据计划中协议ID查询协议
async function getAgreement(number: string) {
  request({
    url: `/srm/core/srmorderschedule/plan/${number}`,
    method: "get",
  })
    .then((data) => {
      Object.assign({}, addDialog.data, data.data);
      console.log(addDialog.data);
      addDialog.visible = true;
    })
    .catch((res) => {
      console.log(res);
    });
}

function importOpen() {
  dialogVisible.value = true;
}

function importClose() {
  dialogVisible.value = false;
}

function synchronizationOpen() {
  synchronization.value = true;
}

function synchronizationClose() {
  synchronization.value = false;
}

// 导入
function excelBoxOpen() {
  excelBox.value = true;
}

// 启用/停用
function isEnabled(row: any) {
  const text = row.enabled === 0 ? "启用" : "停用";
  // 弹出确认提示框
  ElMessageBox.confirm(`确定要${text}此记录吗？`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      loading.value = true; // 显示加载状态
      request({
        url: `/srm/core/srmorderschedule/enabled`,
        method: "post",
        data: row,
      })
        .then((res) => {
          ElMessage.success(`${text}成功`);
          getTableList();
        })
        .catch((res) => {
          return;
        })
        .finally(() => {
          loading.value = false;
        });
    })
    .catch(() => {
      return;
    });
}

function confirm(id: string) {
  request({
    url: `/srm/core/srmorderschedule/confirm`,
    method: "post",
    data: { id: id },
  }).then((res) => {
    ElMessage.success(res.data);
    getTableList();
  });
}

// 批量确认
// function batchConfirm(){
//   console.log(ids.value)
// }
async function batchConfirm() {
  console.log(ids.value);
  await request({
    url: "/srm/core/srmorderschedule/batchConfirm",
    method: "post",
    data: { ids: ids.value },
  }).finally(() => {
    loading.value = false;
  });
  reset();
}

/** 打开订货计划表单弹窗 */
function openDialog(roleObj?: Object) {
  if (roleObj) {
    addDialog.title = "更新订货计划";
    getInfo(roleObj.id);
  } else {
    addDialog.title = "新增订货计划";
    addDialog.visible = true;
  }
  addDialog.readvisible = false;
}

/** 打开订货计划表单弹窗 详情 */
function openDialogdetail(roleObj?: any) {
  addDialog.title = "订货计划详情";
  getInfo(roleObj.id);
  addDialog.readvisible = true;
}

function changeVisible(value: boolean) {
  addDialog.visible = value;
  if (!value) {
    addDialog.data = {};
  }
}

function getarriveDate(data: any) {
  if (data) {
    searchParam.value.arriveDateStart = data[0];
    searchParam.value.arriveDateEnd = data[1];
  } else {
    searchParam.value.arriveDateStart = "";
    searchParam.value.arriveDateEnd = "";
  }
}

// 导入
function getfilepath(e: any) {
  const file = e.target.files[0];
  fileName.value = file.name;
  uploadFile.value = file;
  uploadBtn.value = false;
}

function upload() {
  if (!uploadFile.value) {
    ElMessage({
      type: "warning",
      message: "请选择文件！",
    });
    return;
  }

  let formdata = new FormData();
  formdata.append("file", uploadFile.value);
  let config = { headers: { "Content-Type": "multipart/form-data" } };
  request
    .post(uploadApi, formdata, config)
    .then((res) => {
      ElMessage({
        type: "success",
        message: "上传成功！",
      });

      excelBox.value = false;
      uploadBtn.value = true;
      search();
    })
    .catch((error) => {
      console.log(error);
    });
}
</script>
